#include <at_tools.h>


uint32_t at_chars_to_hex(char * pAscii, uint8_t * pHex, int nLen)
{
    if (nLen % 2)return 0;
    int nHexLen = nLen / 2;
    for (int i = 0; i < nHexLen; i++)
    {
        unsigned char nibble[2];
        nibble[0] = *pAscii++;
        nibble[1] = *pAscii++;
        for (int j = 0; j < 2; j++)
        {
            if (nibble[j] <= 'F' && nibble[j] >= 'A')
                nibble[j] = nibble[j] - 'A' + 10;
            else if (nibble[j] <= 'f' && nibble[j] >= 'a')
                nibble[j] = nibble[j] - 'a' + 10;
            else if (nibble[j] >= '0' && nibble[j] <= '9')
                nibble[j] = nibble[j] - '0';
            else
                return  0;
        }
        pHex[i] = nibble[0] << 4;	// Set the high nibble
        pHex[i] |= nibble[1];	//Set the low nibble
    }
    return nHexLen;	
}

uint32_t at_hex_to_chars(uint8_t *data,uint16_t data_len,uint8_t *hex_char,uint16_t char_buf_len)
{
    uint16_t i=0;
    uint16_t max_data_len=0;
    uint8_t tmp=0;
    max_data_len=(char_buf_len>=(data_len*2))?data_len:char_buf_len/2;
    for(i=0;i<max_data_len;i++)
    {
        tmp=data[i]/16;
        if(tmp<10)hex_char[i*2]=tmp+'0';
        else hex_char[i*2]=tmp-10+'A';
        
        tmp=data[i]%16;
        if(tmp<10)hex_char[i*2+1]=tmp+'0';
        else hex_char[i*2+1]=tmp-10+'A';
    }
    return i*2; 
}

